#include "mainwindow.h"
#include "ui_mainwindow.h"


#define  TOPIC_LED "led002"
#define  TOPIC_FAN "fan003"
#define  TOPIC_H    "H004"
#define  TOPIC_T    "T004"
#define  TOPIC_S    "S004"
#define  TOPIC_SUN  "Sun004"
#define  TOPIC_W    "W009"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(&socket, &QTcpSocket::connected, [&]()
    {
        qDebug() << "Connected to server";

        //post(TOPIC_H, std::to_string(10.01).c_str());
    });

    connect(&socket, &QTcpSocket::readyRead, [&]() {
        QByteArray data = socket.readAll();
        //qDebug() << "recv:" << data;
        parseAndDisplay(data);
    });

    socket.connectToHost("119.91.109.180", 8344);
    //socket.write(data.toUtf8());

    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [&]
    {
        subscribe();
    });
    timer->start(10 *1000);
    ui->pushButton_led->setVisible(false);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::send_command(const char *uid, const char *topics)
{
    char msgbuf[MAX_MSG_SIZE];
    sprintf(msgbuf, "cmd=1&uid=%s&topic=%s\r\n", uid, topics);
    // 假设 socket.write 是一个有效的函数，用于发送数据
    socket.write(msgbuf, strlen(msgbuf));
}

void MainWindow::subscribe()
{
    char topics[MAX_MSG_SIZE];
    int len = 0;

    // 将所有主题合并到一个字符串中，用逗号分隔
    len += snprintf(topics + len, sizeof(topics) - len, "%s", TOPIC_LED);
    len += snprintf(topics + len, sizeof(topics) - len, ",%s", TOPIC_FAN);
    len += snprintf(topics + len, sizeof(topics) - len, ",%s", TOPIC_H);
    len += snprintf(topics + len, sizeof(topics) - len, ",%s", TOPIC_S);
    len += snprintf(topics + len, sizeof(topics) - len, ",%s", TOPIC_W);
    len += snprintf(topics + len, sizeof(topics) - len, ",%s", TOPIC_SUN);
    len += snprintf(topics + len, sizeof(topics) - len, ",%s", TOPIC_T);

    // 发送合并后的主题
    send_command(UID, topics);
}

// 发送 POST 指令的函数
void MainWindow::post(const char *topic, const char *msg, const char *uid)
{
    char msgbuf[MAX_MSG_SIZE];
    int len = snprintf(msgbuf, sizeof(msgbuf), "cmd=2&uid=%s&topic=%s&msg=%s\r\n", uid, topic, msg);
    if (len < 0)
    {
        fprintf(stderr, "Error: Message buffer overflow\n");
        return;
    }
    qDebug() << "post:" << msgbuf;
    socket.write(msgbuf, strlen(msgbuf));

}

// 解析接收到的数据并显示到对应的 label 上
void MainWindow::parseAndDisplay(const QByteArray& data)
{
    // 假设数据格式为 "cmd=2&uid=xxx&topic=xxx&msg=xxx\r\n"
    QString strData = QString::fromUtf8(data);
    QStringList parts = strData.split("&");

    QString topic;
    QString msg;

    for (const QString& part : parts) {
        QStringList keyValue = part.split("=");
        if (keyValue.size() == 2) {
            if (keyValue[0] == "topic") {
                topic = keyValue[1];
            } else if (keyValue[0] == "msg") {
                msg = keyValue[1].trimmed();
            }
        }
    }

    if (!topic.isEmpty() && !msg.isEmpty())
    {
        qDebug() << topic << msg;
        if (topic == TOPIC_LED) {
            if(msg == "false")
                ui->pushButton_led->setText("开灯");
            else
                ui->pushButton_led->setText("关灯");
        }
        else if (topic == TOPIC_FAN)
        {
            if(msg == "false")
                ui->pushButton_fan->setText("打开风扇");
            else
                ui->pushButton_fan->setText("关闭风扇");
        } else if (topic == TOPIC_H)
        {
            ui->label_H->setText(QString("湿度：%1%").arg(QString::number(msg.toDouble(), 'f', 2)));
        }
        else if (topic == TOPIC_T) {
            ui->label_T->setText(QString("温度：%1°C").arg(QString::number(msg.toDouble(), 'f', 2)));
        } else if (topic == TOPIC_SUN) {
            ui->label_L->setText(QString("光照：%1 lux").arg(QString::number(msg.toDouble(), 'f', 2)));
        } else if (topic == TOPIC_S) {
            if(msg.contains("0"))
                ui->label_S->setText("烟雾：正常");
            else
                ui->label_S->setText("烟雾：异常");
        } else if (topic == TOPIC_W)
        {
            if(msg == "false")
                ui->pushButton_window->setText("打开窗帘");
            else
                ui->pushButton_window->setText("关闭窗帘");
        }
    }
}

void MainWindow::on_pushButton_window_clicked()
{
    if(ui->pushButton_window->text() == "打开窗帘")
    {
        ui->pushButton_window->setText("关闭窗帘");
        post(TOPIC_W, "true");
    }
    else
    {
        ui->pushButton_window->setText("打开窗帘");
        post(TOPIC_W, "false");
    }
}

void MainWindow::on_pushButton_led_clicked()
{
    if(ui->pushButton_led->text() == "开灯")
    {
        ui->pushButton_led->setText("关灯");
        post(TOPIC_LED, "true");
    }
    else
    {
        ui->pushButton_led->setText("开灯");
        post(TOPIC_LED, "false");
    }
}

void MainWindow::on_pushButton_fan_clicked()
{
    if(ui->pushButton_fan->text() == "打开风扇")
    {
        ui->pushButton_fan->setText("关闭风扇");
        post(TOPIC_FAN, "true");
    }
    else
    {
        ui->pushButton_fan->setText("打开风扇");
        post(TOPIC_FAN, "false");
    }
}
